package com.freesun.shop.service.impl;


import cn.hutool.core.lang.Snowflake;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.freesun.shop.domin.Pay;
import com.freesun.shop.entity.Order;
import com.freesun.shop.entity.OrderItem;
import com.freesun.shop.mapper.OrderItemMapper;
import com.freesun.shop.mapper.OrderMapper;
import com.freesun.shop.service.AliPayService;
import com.freesun.shop.service.BasketService;
import com.freesun.shop.service.OrderService;
import com.freesun.shop.service.SkuService;
import com.freesun.shop.vo.OrderResultVo;
import com.freesun.shop.vo.ShopCartItem;
import org.apache.activemq.ScheduledMessage;
import org.apache.dubbo.config.annotation.Reference;
import org.apache.dubbo.config.annotation.Service;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.jms.core.JmsTemplate;
import org.springframework.jms.core.MessagePostProcessor;

import javax.jms.JMSException;
import javax.jms.Message;
import java.math.BigDecimal;
import java.time.LocalDateTime;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * <p>
 * 订单表 服务实现类
 * </p>
 *
 * @author zf
 * @since 2019-11-13
 */
@Service
public class OrderServiceImpl extends ServiceImpl<OrderMapper, Order> implements OrderService {

    @Autowired
    private OrderMapper orderMapper;
    @Autowired
    private OrderItemMapper orderItemMapper;
    @Reference(check = false)
    private SkuService skuService;
    @Reference(check = false)
    private BasketService basketService;
    @Reference(check = false)
    private AliPayService aliPayService;
    @Autowired
    private Snowflake snowflake;

    //消息队列
    @Autowired
    private JmsTemplate jmsTemplate;

    /**
     * 生成一个预订单
     *
     * @param orderVo
     * @return
     */
    @Override
    public String createPreOrder(OrderResultVo orderVo) {
        //得到本次要购买的所有商品
        List<ShopCartItem> shopCartItems = orderVo.getShopCartOrders().get(0).getShopCartItemDiscounts().get(0).getShopCartItems();
        //哪个商品库存减少多少的值
        Map<Long, Integer> skuCount = new HashMap<>();
        List<Long> basketIds = new ArrayList<>();
        StringBuilder stringBuilder = new StringBuilder();
        shopCartItems.forEach(shopCartItem -> {
            skuCount.put(shopCartItem.getSkuId(), shopCartItem.getProdCount());
            basketIds.add(shopCartItem.getBasketId());
            stringBuilder.append(shopCartItem.getProdName()).append(",");
        });
        //删除拼接的最后一个，号
        stringBuilder.deleteCharAt(stringBuilder.length() - 1);
        //清空库存和购物车
        stockAndCart(skuCount, basketIds);
        //雪花算法生成订单号
        String orderId = snowflake.nextIdStr();
        //生成订单和订单商品中间表
        writeOrder(orderId, orderVo, shopCartItems, stringBuilder);
        //5.设置订单的超时时间 放在延时队列里面，若订单没有支付，删除订单，并回退库存

        serOrderExpire(orderId);
        //6.为该订单生成一个支付连接
        String prePay = getPayInfo(orderId, orderVo.getActualTotal(), stringBuilder);
        //7.返回该连接
        return prePay;
    }

    private String getPayInfo(String orderId, BigDecimal total, StringBuilder stringBuilder) {
        Pay pay = new Pay();
        pay.setPayType(1);
        pay.setOutTradeNo(orderId);
        pay.setBody(stringBuilder.toString());
        pay.setTotalAmount(total.toString());
        pay.setSubject("EGO商城:" + orderId + "订单");
        return aliPayService.prePay(pay);
    }

    private void serOrderExpire(String orderSn) {
        //new MessagePostProcessor()//消息处理器
        jmsTemplate.convertAndSend("order.pre.queue", orderSn, new MessagePostProcessor() {
            @Override
            public Message postProcessMessage(Message message) throws JMSException {
                message.setLongProperty(ScheduledMessage.AMQ_SCHEDULED_DELAY, 30 * 60 * 1000);
                return message;
            }
        });
    }

    private void writeOrder(String orderId, OrderResultVo orderVo, List<ShopCartItem> shopCartItems, StringBuilder stringBuilder) {
        //3.写订单
        Order order = new Order();
        //设置订单编号
        order.setOrderNumber(orderId);
        //设置订单的实际金额
        order.setActualTotal(orderVo.getActualTotal());
        //设置订单的总金额
        order.setTotal(orderVo.getTotal());
        order.setProdName(stringBuilder.toString());
        order.setIsPayed(false);
        order.setPayType(1); //支付宝网页支付
        order.setProductNums(orderVo.getTotalCount());

        orderMapper.insert(order);
        //4.写订单和商品的中间表
        shopCartItems.forEach(shopCartItem -> {
            OrderItem orderItem = new OrderItem();
            orderItem.setOrderNumber(orderId);
            orderItem.setProdId(shopCartItem.getProdId());
            orderItem.setSkuId(shopCartItem.getSkuId());
            orderItem.setSkuName(shopCartItem.getSkuName());
            orderItem.setProdName(shopCartItem.getProdName());
            orderItem.setProductTotalAmount(shopCartItem.getPrice().multiply(new BigDecimal(shopCartItem.getProdCount())));
            orderItem.setPrice(shopCartItem.getPrice());
            orderItem.setRecTime(LocalDateTime.now());
            orderItem.setPic(shopCartItem.getPic());
            // orderItem.setUserId();
            orderItemMapper.insert(orderItem);
        });
    }

    private void stockAndCart(Map<Long, Integer> skuCount, List<Long> basketIds) {
        //1.扣减库存
        skuService.decrStok(skuCount);
        //2.清空购物车
        basketService.clearItem(basketIds);
    }
}
